#手写线性回归类

import numpy as  np

from sklearn.preprocessing import MaxAbsScaler

class LinearRegression:

    def __init__(self,max_iter=100000):

        self.coef_ = None

        self.intercept_ = None

        self.iter = max_iter

        self.learning_rate = 0.001

        self.ss = None

 

    def fit(self,X,y):

        X = np.array(X)

        y = np.array(y).reshape(-1,1)

        X_new = np.column_stack(tup =(np.ones(shape=(X.shape[0],1)),X))

#

        w = np.random.random_integers(-20,20,X_new.shape[1]).reshape(-1,1)

        for i in range(self.iter):

            gradient = np.zeros(shape=(X_new.shape[1], 1))

            for j in range(len(gradient)):

                gradient[j, 0] = 2 / X_new.shape[0] * ((X_new @ w) - y).T @ X_new[:,j]

            w = w -  gradient * self.learning_rate

        self.coef_ = w

        self.intercept_ = w[0]

 

    def predict(self,X):

        X = np.array(X)

        X_new = np.column_stack(tup=(np.ones(shape=(X.shape[0], 1)), X))

        #

        y_predict =  X_new @ self.coef_

        return y_predict
    

    